import { defineComponent, onMounted, reactive, ref,} from "vue";
import styles from "./insureExportSonPage.module.less";
import {$groupOrderInsuredPeopleList,$groupOrderInsuredPeople} from "@/api/groupOrder/groupOrder"
import Page from "@/components/public/page/page";
import { CardWithTitle } from "@/components/public/card/card";
import useXlsx from "@/hooks/useXlsx";
import {
  DoubleRightOutlined,
  CheckOutlined,
} from "@ant-design/icons-vue";
import { message, Progress, Spin, } from "ant-design-vue";
import { Modal } from "ant-design-vue";
import useNavigator from "@/hooks/useNavigator";
export default defineComponent({
  emits: ["cancel", "confirm"],
  setup(props, { emit, expose }) {
    const xlsx = useXlsx();
    const visible = ref(false);
    const numberProgress = ref(0);
    const title = ref("" as any);
    const navigator = useNavigator();
    const state = reactive({
      nextIndex: 0,
      datelist:[],
      datalist: [],
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          key: "id",
          align: "center",
        },
        {
          title: "保司保单号",
          dataIndex: "insurance_order_no",
          key: "insurance_order_no",
          align: "center",
        },
        {
          title: "系统订单号",
          dataIndex: "order_no",
          key: "order_no",
          align: "center",
        },
        {
          title: "续保/终保",
          dataIndex: ["is_new", "label"],
          key: "is_new",
          align: "center",
        },
        {
          title: "被保人姓名",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "身份证号码",
          dataIndex: "id_no",
          key: "id_no",
          align: "center",
        },
        {
          title: "生日",
          dataIndex: "birthday",
          key: "birthday",
          align: "center",
        },
        {
          title: "性别",
          dataIndex: ["sex", "label"],
          key: "sex",
          align: "center",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          key: "mobile",
          align: "center",
        },
        {
          title: "所在市",
          dataIndex: ["city_id", "label"],
          key: "city_id",
          align: "center",
        },
        {
          title: "所在区县",
          dataIndex: ["area_id", "label"],
          key: "area_id",
          align: "center",
        },
        {
          title: "所在乡镇/街道",
          dataIndex: ["street_id", "label"],
          key: "street_id",
          align: "center",
        },
        {
          title: "所在村/社区",
          dataIndex: ["village_id", "label"],
          key: "village_id",
          align: "center",
        },
        {
          title: "商保/低保",
          dataIndex:["people_type","label"],
          align: "center",
          width: "180px",
        },
        {
          title: "生效时间",
          dataIndex: "people_start_date",
          key: "people_start_date",
          align: "center",
        },
        {
          title: "承保时间",
          dataIndex: "insure_time",
          key: "insure_time",
          align: "center",
        },
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);
    const cancelHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        navigator.back();
      } else if (state.nextIndex == 1) {
        state.datelist = [];
        state.nextIndex = 0;
      }
    };
    const confirmHandler = async () => {
        if(state.nextIndex == 0)
        {
           if(state.datelist.length != 2)
           {
              message.error("开始日期或结束日期有误")
              return
           }
           $groupOrderInsuredPeopleList({
            start_date_begin:state.datelist[0],
            start_date_end:state.datelist[1],
            page: state.pagination.current,
            limit: state.pagination.pageSize,
           }).then((res:any)=>{
              state.nextIndex = 1;
              state.pagination.total = res.data?.total;
              state.datalist = res.data?.data || [];
           })
        }
        else if(state.nextIndex == 1)
        {
          title.value = "正在导出文件...";
          xlsx.init({
            limit: 2000,
            otherParams:{start_date_begin:state.datelist[0],
              start_date_end:state.datelist[1],},
            service: $groupOrderInsuredPeopleList
          })
          await xlsx.defineList([
            {
              label: '系统保单号',
              value: 'order_no',
              width: 25,
            },
            {
              label: '保司保单号',
              value: 'insurance_order_no',
              width: 25,
            },
            {
              label: '被保人姓名',
              value: 'name',
              width: 25,
            },
            {
              label: '证件号码',
              value: 'id_no',
              width: 25,
            },
            {
              label: '本次生效日期',
              value: 'people_start_date',
              width: 25,
            },
            {
              label: '承保时间',
              value: 'insure_time',
              width: 25,
            },
          ]);
          await xlsx.exportToExcel('团单承保.xlsx');
        }
    };
    //承保导出查询
    const ExportSearch = (e:any)=>{
      $groupOrderInsuredPeople({
        start_date_begin:state.datelist[0],
        start_date_end:state.datelist[1],
        number:e,
       }).then((res:any)=>{
        numberProgress.value = (res?.data?.finish || 0) / (res?.data?.total || 0) * 100;
        if(res?.data?.status === 1)
        {
           window.open(res.data.url);
        }
        else if(res?.data?.status === 10)
        {
           ExportSearch(e);
        }
        else if(res?.data?.status == -1)
        {
            message.error("导出失败,请联系技术人员");
        }
       })
    }
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
      $groupOrderInsuredPeopleList({
        start_date_begin:state.datelist[0],
        start_date_end:state.datelist[1],
        page: state.pagination.current,
        limit: state.pagination.pageSize,
       }).then((res:any)=>{
          state.pagination.total = res.data?.total;
          state.datalist = res.data?.data || [];
       })
    };
    // 选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      state.selectedRowKeys = changableRowKeys;
    };
    const addPopupRef = ref(null as any);
    const open = (e: any) => {
      state.nextIndex = 0;
      state.datelist = [];
      state.pagination.current = 1;
      state.pagination.pageSize = 10;
      visible.value = false;
      numberProgress.value = 0;
      addPopupRef.value.open();
    };
    const close = () => {
      addPopupRef.value.close();
    };
    expose({
      open,
      close,
    });
    onMounted(()=>{
      state.nextIndex = 0;
      state.datelist = [];
      state.pagination.current = 1;
      state.pagination.pageSize = 10;
      visible.value = false;
      numberProgress.value = 0;
    })
    //承保清单
    const Exportlist = () => (
      <div class={styles.uploadChecklist_box}>
        <div class={styles.head_box}>
          <div class={styles.head_left_box}>
          {state.nextIndex > 0 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                ]}
              >
                1
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>选择基础信息</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            {state.nextIndex > 1? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 1 && styles.numberOne_current_box,
                ]}
              >
                2
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>确认团单信息</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
        </div>
         <div class={styles.body_box}>
          {state.nextIndex == 0 && (
            <div class={styles.content_box}>
                  <div class={styles.content_left_box}>选择生效时间范围:</div>
                  <div class={styles.content_right_box}>
                  <a-range-picker  onChange={(e:any,dateStrings:any)=>{
                    state.datelist = dateStrings;
          }}/>
                  </div>
            </div>
          )}
          {state.nextIndex > 0 && (
            <div class={styles.group_box}>
              <Grouplist />
            </div>
          )}
        </div>
      </div>
    );
    //上传团单列表结果
    const Grouplist = () => (
      <div style={{ width: "100%" }}>
        <a-table
          dataSource={state.datalist}
          columns={state.columns}
          pagination={state.pagination}
          scroll={{ x: 2000 }}
          onChange={tableChangeHandler}
          v-slots={{
            bodyCell: ({ column, record }: any) => {
            },
          }}
        />
      </div>
    );
    const Components = () => (
      <Page>
        <CardWithTitle title="承保导出">
        <div class={styles.orderEntryAdd}>
            <Exportlist />
          <div class={styles.btn_Box}>
            <a-button
              size="small"
              style={{ width: "55px" }}
              onClick={() => cancelHandler()}
            >
           {
             state.nextIndex == 0
                ? "取消"
                : "上一步"}
            </a-button>
            <div class={styles.right_btn_box}>
                <a-button
                  type="primary"
                  size="small"
                  onClick={() => confirmHandler()}
                >
                  {
                     state.nextIndex == 0 ? "下一步":"导出清单"
                  }
                </a-button>
             </div>
             {
               state.nextIndex == 1 && (
                <div class={styles.right_btn_box}>
                <a-button
                  size="small"
                  style={{ width: "55px" }}
                  onClick={() => {
                    navigator.back();
                  }}
                >
                  返回
                </a-button>
             </div>
               )
             }
          </div>
        </div>
      </CardWithTitle>
      {
             <Modal
             title={title.value}
             visible={['doing'].includes(xlsx.state.running)}
             closable={false}
             footer={null}
           >
              <div class={styles["progress_box"]}>
               {
                 xlsx.state.running === "doing" && xlsx.progress.value < 100 && (
                   <Progress type="circle" percent={xlsx.progress.value} />
                 )
               }
               {
                 xlsx.state.running === "doing" && xlsx.progress.value === 100 && (
                   <Spin tip="正在导出文件,请勿关闭当前页面..." size="large" />
                 )
               }
             </div>
           </Modal>
            }
      </Page>
      
    );
    return {
      Components,
    };
  },
  render() {
    return <this.Components />;
  },
});